package org.example.market.service;

import org.example.market.entity.Address;
import org.example.market.mapper.AddressMapper;
import org.example.market.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressService {

    @Autowired
    private AddressMapper addressMapper;

    public Result<Address> addAddress(Address address) {
        try {
            addressMapper.insertAddress(address);
            return Result.success(address);
        } catch (Exception e) {
            return Result.error(500, "添加地址失败: " + e.getMessage());
        }
    }

    public Result<Void> deleteAddress(Long id) {
        try {
            addressMapper.deleteAddressById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "删除地址失败: " + e.getMessage());
        }
    }

    public Result<Address> updateAddress(Address address) {
        try {
            addressMapper.updateAddress(address);
            return Result.success(address);
        } catch (Exception e) {
            return Result.error(500, "更新地址失败: " + e.getMessage());
        }
    }

    public Result<Address> getAddressById(Long id) {
        try {
            Address address = addressMapper.getAddressById(id);
            if (address != null) {
                return Result.success(address);
            }
            return Result.error(404, "未找到该地址");
        } catch (Exception e) {
            return Result.error(500, "获取地址详情失败: " + e.getMessage());
        }
    }

    public Result<List<Address>> getAddressesByUserId(Long userId) {
        try {
            List<Address> addresses = addressMapper.getAddressesByUserId(userId);
            return Result.success(addresses);
        } catch (Exception e) {
            return Result.error(500, "获取用户地址列表失败: " + e.getMessage());
        }
    }
}